/*
 * @Author: curse-the-west m18811101669@163.com
 * @Date: 2022-08-04 16:03:29
 * @LastEditors: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @LastEditTime: 2022-10-21 09:02:29
 * @FilePath: /day19/egg_dome/app/middleware/auth.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const jwt = require('jsonwebtoken');

const whiltList = ['/login', '/sign', ];


const auth = (options, app) => {
    return async (ctx, next) => {

        // 白名单
        if (whiltList.includes(ctx.path)) {
            await next();
        } else {
            let token = ctx.request.header.authorization;
            if (token) {
                try {
                    const res = jwt.verify(token, 'gzd');
                    console.log(res);
                    await next();
                } catch (err) {
                    if (err.message === 'jwt expired') {
                        ctx.body = {
                            code: 401,
                            msg: 'token过期，请重新登陆',
                            err
                        }
                    } else {
                        ctx.body = {
                            code: 400,
                            msg: 'token失败！请重新登陆',
                            err
                        }
                    }

                }
            } else {
                ctx.body = {
                    code: 302,
                    msg: '无token值'
                }
            }

        }
    }
}

module.exports = auth